﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace Zeus.Comunicaciones.Entidades
{
    public class CompositeEntity : List<EntityProperty>
    {
        public object GetValue(string key)
        {
            return this.Single(t => t.Key == key).Value;
        }

        public object GetValue()
        {
            return this.First().Value;
        }

        public T GetValue<T>(string key)
        {
            return (T)GetValue(key);
        }

        public EntityProperty GetProperty(string key)
        {
            return this.Single(t => t.Key == key);
        }

        public static CompositeEntity From(DataRow source)
        {
            CompositeEntity composite = new CompositeEntity();

            foreach (DataColumn column in source.Table.Columns)
            {
                EntityProperty property = new EntityProperty
                {
                    Key = column.ColumnName,
                    Value = source[column.ColumnName]
                };

                composite.Add(property);
            }

            return composite;
        }

        public static CompositeEntity From(IDictionary source)
        {
            CompositeEntity composite = new CompositeEntity();

            foreach (object key in source.Keys)
            {
                EntityProperty property = new EntityProperty
                {
                    Key = key.ToString(),
                    Value = source[key]
                };

                composite.Add(property);
            }

            return composite;
        }

        public static CompositeEntity From(object source, string key = null)
        {
            CompositeEntity composite = new CompositeEntity();

            key = string.IsNullOrEmpty(key) ? source.GetType().Name : key;

            composite.Add(new EntityProperty { Key = key, Value = source });

            return composite;
        }

        public static List<CompositeEntity> From(DataTable source)
        {
            List<CompositeEntity> compositeList = new List<CompositeEntity>();

            source.AsEnumerable().ToList().ForEach(t => compositeList.Add(From(t)));

            return compositeList;
        }
    }
}
